package org.example.corpus.auth.controller;


import lombok.extern.slf4j.Slf4j;

import org.apache.poi.ss.formula.functions.T;
import org.example.corpus.auth.controller.dto.UserDto;
import org.example.corpus.common.ResponseResult;
import org.example.corpus.model.User;
import org.example.corpus.auth.service.UserService;
import org.example.corpus.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/users")
@Component
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    // 创建用户
    @PostMapping
    public ResponseResult createUser(@RequestBody UserDto userDto) {
        User user =new User();
        user.setUsername(userDto.getUsername());
        user.setPassword(userDto.getPassword());
        Integer ret=userService.register(user);
        if(ret==1){
            return ResponseResult.success();
        }else if (ret==2)
        {

            return ResponseResult.error("用户名已存在");
        }
        else {
            return ResponseResult.error("创建失败");
        }
    }

    // 用户登录
    @PostMapping("/login")
    public ResponseResult<Object> login(@RequestParam String username, @RequestParam String password) {
        User user=userService.login(username,password);
        if(user!=null){
            Map<String,Object> claims=new HashMap<>();
            claims.put("username",user.getUsername());
            claims.put("id",user.getId());
            String token= JwtUtil.genToken(claims);
            return ResponseResult.success(token,"登录成功");
        }else{
            return ResponseResult.error("登录失败");
        }
    }
}
